package xin.alum.aim.coder;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import xin.alum.aim.constant.ChannelAttr;
import xin.alum.aim.model.Transportable;
import xin.alum.aim.model.proto.Packet;

import java.util.List;

public class WebEncoder extends BaseEncoder<Transportable> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Transportable in, List<Object> list) {
        Packet.Agreement agreement = ctx.channel().attr(ChannelAttr.AGREEMENT).get();
        if (agreement == null) {
            logger.error("{}未初始化通信协议", ctx.channel());
            return;
        }

        switch (agreement) {
            case Json:
            case Text:
                list.add(new TextWebSocketFrame(in.toString()));
                break;
            case Binary:
            case ProtoBuf:
                byte[] binary = in.getBody();
                ByteBufAllocator binAlloc = ctx.channel().config().getAllocator();
                ByteBuf binOut = binAlloc.buffer(binary.length);
                binOut.writeBytes(binary);
                list.add(new BinaryWebSocketFrame(binOut));
                break;
            default:
                logger.error("{}未知编码协议：{}", ctx.channel(), agreement);
                break;
        }
    }
}
